/**
 Copyright (c) 2007, Fanhuagang

 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, 
 are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this list 
 of conditions and the following disclaimer. 
 Redistributions in binary form must reproduce the above copyright notice, this 
 list of conditions and the following disclaimer in the documentation and/or other 
 materials provided with the distribution. 
 Neither the name of the Fanhuagang nor the names of its contributors may be used 
 to endorse or promote products derived from this software without specific prior 
 written permission. 

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
package van.index;

import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.application.PathManager;
import org.apache.lucene.index.IndexReader;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * This is a maven repository index manager. it use to two inner IndexerJob and UnpackerJob to do
 * index job.
 * <p/>
 * IndexerJob and UnpackerJob always schedule a background job to the real things.
 * <p/>
 * User: Fanhuagang
 * Date: 2007-11-3
 * Time: 11:31:10
 */
public class MavenRepositoryIndexManager {
    private static final String LOCAL_INDEX = "local";

    private static final String[] DEFAULT_INDEXES = {"central"};

    private Set<String> indexes = Collections.synchronizedSet(new HashSet<String>());

    private IndexerJob localIndexer;

    public MavenRepositoryIndexManager() {

        File indexDir = getIndexDir();

        UnpackerJob unpackerJob = new UnpackerJob(indexDir, DEFAULT_INDEXES, indexes);
        unpackerJob.schedule(2000L);

        File localRepositoryIndexDir = new File(indexDir, LOCAL_INDEX);
        if (localRepositoryIndexDir.exists()) {
            IndexReader reader = null;
            try {
                reader = IndexReader.open(localRepositoryIndexDir);
                indexes.add(LOCAL_INDEX);
            } catch (Exception ex) {
                reindexLocal(5000L);
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException ex) {
                    // ignore
                }
            }

        } else {
            reindexLocal(5000L);
        }
    }

    public File[] getIndexes() {
        String[] indexNames = getIndexNames();

        File[] indexes = new File[indexNames.length];
        for (int i = 0; i < indexes.length; i++) {
            indexes[i] = new File(getIndexDir(), indexNames[i]);
        }

        return indexes;
    }

    public void reindexLocal(long delay) {
        if (localIndexer == null || localIndexer.isDone()) {
            localIndexer = new IndexerJob(LOCAL_INDEX, indexes, getIndexDir());
        }
        localIndexer.reindex(getLocalRepositoryDir(), delay);
    }

    private File getLocalRepositoryDir() {
        return new File(System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository");
    }

    public synchronized void updateIndex(File localFile, String repository, String name, long size, long date) {
        String indexPath = new File(getIndexDir(), LOCAL_INDEX).getAbsolutePath();
        try {
            Indexer indexer = new Indexer();
            indexer.addDocument(repository, name, size, date, indexer.readNames(localFile), indexPath);
        } catch (IOException ex) {
            String msg = "Unable to index " + name;
            System.err.println(msg);
        }
    }

    private File getIndexDir() {
        File file = new File(PathManager.getSystemPath());
        file = new File(file, "plugins");
        file = new File(file, "MavenProjectHelper");
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(file, "index");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    private URL getEntry(String name) {
        File file = new File(PathManager.getConfigPath());
        file = new File(file, "plugins");
        file = new File(file, "MavenProjectHelper");
        try {
            return new File(file, name).toURI().toURL();
        } catch (MalformedURLException e) {
            System.err.println(e.getMessage());
        }
        return null; // todo: may cause NPE
    }

    // TODO implement index registry
    private String[] getIndexNames() {
        return indexes.toArray(new String[indexes.size()]);
    }


    class UnpackerJob {
        private final File indexDir;
        private final Set<String> indexes;
        private final String[] indexNames;

        public UnpackerJob(File indexDir, String[] indexNames, Set<String> indexes) {
            this.indexDir = indexDir;
            this.indexNames = indexNames;
            this.indexes = indexes;
        }

        public void schedule(long delay) {
            JobScheduler.getScheduler().schedule(new Runnable() {
                public void run() {
                    for (String name : indexNames) {
                        File index = new File(indexDir, name);
                        if (!index.exists()) {
                            index.mkdirs();
                        } else {
                            File[] files = index.listFiles();
                            for (File file : files) {
                                file.delete();
                            }
                        }

                        URL indexArchive = getEntry(name + ".zip");
                        InputStream is = null;
                        ZipInputStream zis = null;
                        try {
                            is = indexArchive.openStream();
                            zis = new ZipInputStream(is);
                            ZipEntry entry;
                            byte[] buf = new byte[4096];
                            while ((entry = zis.getNextEntry()) != null) {
                                File indexFile = new File(index, entry.getName());
                                FileOutputStream fos = null;
                                try {
                                    fos = new FileOutputStream(indexFile);
                                    int n = 0;
                                    while ((n = zis.read(buf)) != -1) {
                                        fos.write(buf, 0, n);
                                    }
                                } finally {
                                    close(fos);
                                }
                            }
                            indexes.add(name);
                        } catch (Exception ex) {
                            System.err.println("Unable to initialize indexes" + ex.getMessage());

                        } finally {
                            close(zis);
                            close(is);
                        }
                    }
                }
            }, delay, TimeUnit.MILLISECONDS);
        }

        private void close(InputStream is) {
            try {
                if (is != null)
                    is.close();
            } catch (IOException ex) {
            }
        }

        private void close(OutputStream os) {
            try {
                if (os != null)
                    os.close();
            } catch (IOException ex) {
            }
        }
    }


    class IndexerJob {
        private final String repositoryName;
        private final Set<String> indexes;
        private final File indexDir;

        private File repositoryDir;

        private transient ScheduledFuture scheduledFuture;

        public IndexerJob(String repositoryName, Set<String> indexes, File indexDir) {
            this.repositoryName = repositoryName;
            this.indexes = indexes;
            this.indexDir = indexDir;
        }

        public boolean isDone() {
            return scheduledFuture == null || scheduledFuture.isDone();
        }

        public void reindex(File localRepositoryDir, long delay) {
            this.repositoryDir = localRepositoryDir;

            if (isDone()) {
                scheduledFuture = JobScheduler.getScheduler().schedule(new Runnable() {
                    public void run() {
                        while (repositoryDir != null) {
                            String repositoryPath = repositoryDir.getAbsolutePath();
                            repositoryDir = null;
                            try {
                                File file = new File(indexDir, repositoryName);
                                if (!file.exists()) {
                                    file.mkdirs();
                                }

                                Indexer indexer = new Indexer();
                                indexer.reindex(file.getAbsolutePath(), repositoryPath, repositoryName);
                                indexes.add(repositoryName);

                            } catch (IOException ex) {
                                // donothing
                            }
                        }
                    }
                }, delay, TimeUnit.MILLISECONDS);
            }

        }
    }
}
